package com.learn.controller.user;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;

public class BaseController {
	private Logger log = Logger.getLogger(BaseController.class);

	/**
	 * 返回json格式数据
	 * 
	 */
	protected void writeJson(String data, HttpServletResponse res) {
		writeJson(data, res, "utf-8");
	}

	protected void writeJson(String data, HttpServletResponse res,
			String charset) {
		res.setContentType("text/html; charset=" + charset.toLowerCase());
		PrintWriter pw = null;
		try {
			pw = res.getWriter();
			pw.print(data);
			pw.flush();
			pw.close();
		} catch (IOException e) {
			log.error(e.getMessage());
		} finally {
			if (null != pw) {
				pw.close();
			}
		}
	}

	/**
	 * 获取json数据，返回对象
	 * 
	 */
	protected <T> T objectFromJson(String jsonString, Class<T> cls) {
		return JSON.parseObject(jsonString, cls);
	}

	//vo为返回的数据对象
	protected void writeString(HttpServletResponse response, String str) {
		writeJson(JSON.toJSONString(str), response, "utf-8");
	}

}
